import { setToken, getToken, removeToken } from '../../utils/auth'

import { login, getprofile, getUserDetailById } from '@/api/user'
export default {
  namespaced: true,
  state: {
    // 如果本地有token就取本地token
    token: getToken() || null,
    userInfo: {}
  },
  mutations: {
    // 设置token
    setToken(state, newToken) {
      state.token = newToken
      // token保存到本地
      setToken(newToken)
    },
    // 删除token
    removeToken(state) {
      state.token = null
      // 删除本地token
      removeToken()
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    removeUserInfo(state) {
      state.userInfo = {}
    }

  },
  actions: {
    // 获取token
    async userLogin(context, userInfo) {
      console.log(userInfo)
      const res = await login(userInfo)
      console.log(res.data)
      context.commit('setToken', res.data)
    },
    // 获取用户信息
    async getUserInfo(context) {
      console.log('用户信息', context)
      const res = await getprofile(context)
      const resimg = await getUserDetailById(res.data.userId)
      console.log('头像', resimg.data)
      context.commit('setUserInfo', { ...res.data, ...resimg.data })
      return res.data.roles.menus
    },
    userLogout(context) {
      context.commit('removeUserInfo')
      context.commit('removeToken')
    }
  }
}
